/**
 * JS
 */
angular.module('usercenter.module.auth', [])

    .config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
        $stateProvider
            .state('ucboot.register', {
                url: '/register',
                templateUrl: uc_templateprefix + 'auth/register.html',
                controller: 'RegisterController'
            })
            .state('ucboot.login', {
                url: '/login/:way',
                templateUrl: uc_templateprefix + 'auth/login.html',
                resolve: {
                    login: ['AuthService', function (AuthService) {
                        if (AuthService.getUserid() != '') {//有id则表示已经登录过。
                            return true;
                        } else {
                            return false;
                        }
                    }]
                },
                controller: 'LoginController'
            })
            .state('ucboot.retrievepassword', {
                url: '/retrievepassword',
                templateUrl: uc_templateprefix + 'auth/retrievepassword.html',
                controller: 'RetrievepasswordController'
            })
            .state('ucboot.wxuc', {
                url: '/wxuc',
                templateUrl: uc_templateprefix + 'auth/wxuc.html',
                controller: 'WxucController'
            })
        ;
    }])

    //登录页面控制器
    .controller('LoginController', ['$scope', '$state', '$window', '$stateParams', 'AuthService', 'login', function ($scope, $state, $window, $stateParams, AuthService, login) {
        UserChange(2);
        $scope.wxlogin =function(){
            if($storage.wxpay_openid){
                $state.go("ucboot.wxuc");
            }else{
                window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx43756321dbcb0dda&redirect_uri='+projectBaseUrl+'wxuc&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect';
            }
        };
        var state = login;//登录状态
        if (state == true) {
            $state.go('ucboot.myview');
            return;
        }
        $scope.uc_enturl = projectBaseUrl;
        $scope.user = {};
        $scope.login = function () {
            $scope.user.password = hex_md5($scope.user.password);
            AuthService.login($scope.user, function (data) {
                $storage.userId = data.userid;
                $storage.name = data.name;
                AuthService.shopCarMessage();
                setTimeout(function(){
                    if ($stateParams.way == 0 && $stateParams.way != '') {
                        $state.go("ucboot.myview");
                    } else {
                        $window.history.back();
                    }
                },500);
            }, function (error) {
                input_alert("用户名或者密码错误，请重新登录！");
            });
        }
    }])

    //注册页面控制器
    .controller('RegisterController', ['$scope', '$state', 'AuthService', function ($scope, $state, AuthService) {
        $scope.uc_enturl = projectBaseUrl;
        UserChange(2);
        $scope.user = "";
        $scope.getcode = function (phone) {
            var ph = $(".tel").val();
            var nam = $(".name").val();
            var fist = nam.substring(1, 0);
            var pas = $(".psw").val();
            var flag = false;
            var myreg = /^(((13[0-9]{1})|(14[0-9]{1})|(17[0-9]{1})|(15[0-3]{1})|(15[5-9]{1})|(18[0-9]{1}))+\d{8})$/;
            if (ph == '') {
                input_alert("手机号码不能为空！");
                $(".tel").focus();
            } else if (ph.length != 11) {
                input_alert("请输入有效的手机号码！");
                $(".tel").focus();
                $(".tel").select();
            } else if (!myreg.test(ph)) {
                input_alert("请输入有效的手机号码！");
                $(".tel").focus();
                $(".tel").select();
            } else if (checkPhoneIsExist()) {
                if (nam.length == 0) {
                    input_alert("用户名不能为空！");
                    $(".name").focus();
                }
                else if (nam.length < 2 || nam.length > 16) {
                    input_alert("用户名限2-16字符之间！")
                    $(".name").focus()
                    $(".name").select()
                }
                else if (!fist.match(/^[\u4E00-\u9FA5a-zA-Z]/)) {
                    input_alert("用户名只能以英文字母或汉字开头！")
                    $(".name").focus()
                    $(".name").select()
                }
                else if (!nam.match(/^[\u4E00-\u9FA5a-zA-Z0-9]+$/)) {
                    $(".name").focus()
                    $(".name").select()
                    input_alert("用户名不能为特殊符号！")
                }
                else {
                    if (pas.length == 0) {
                        input_alert("密码不能为空！");
                        $(".psw").focus();
                    }
                    else if (pas.length < 8 || pas.length > 24) {
                        input_alert("密码限8-24字符之间！");
                        $(".psw").focus();
                        $(".psw").select();
                    } else {
                        AuthService.getcode(phone);
                        settime();
                    }
                }
            } else {
                flag = true;
            }
            return flag;
        }
        $scope.register = function () {
            $scope.user.password = hex_md5($scope.user.password);
            AuthService.register($scope.user, function (data) {
                input_alert('注册成功', 1000);
                setTimeout(function () {
                    $state.go("ucboot.myview");
                }, 1000)
                $storage.userId = data.userid;
                $storage.name = data.name;
            }, function (data) {
                input_alert("注册失败！" + data.data.reason);
            });
        }
    }])
    //找回密码页面控制器
    .controller('RetrievepasswordController', ['$scope', '$state', 'AuthService', function ($scope, $state, AuthService) {
        $scope.uc_enturl = projectBaseUrl;
        UserChange(2);
        $scope.user = {};
        $scope.password = {};
        $scope.getcode = function (phone) {
            var ph = $(".tel").val();
            var flag = false;
            var myreg = /^(((13[0-9]{1})|(14[0-9]{1})|(17[0-9]{1})|(15[0-3]{1})|(15[5-9]{1})|(18[0-9]{1}))+\d{8})$/;
            if (ph == '') {
                input_alert("手机号码不能为空！");
                $(".tel").focus();
            } else if (ph.length != 11) {
                input_alert("请输入有效的手机号码！");
                $(".tel").focus();
                $(".tel").select();
            } else if (!myreg.test(ph)) {
                input_alert("请输入有效的手机号码！");
                $(".tel").focus();
                $(".tel").select();
            } else if (checkPhoneIsExist()) {
                AuthService.getcode(phone);
                settime();
            } else {
                flag = true;
            }
            return flag;

        }
        //提交
        $scope.retrieve = function () {
            var pas = $(".psw").val();
            if (pas.length == 0) {
                input_alert("密码不能为空！");
                $(".psw").focus();
            }
            else if (pas.length < 8 || pas.length > 24) {
                input_alert("密码限8-24字符之间！");
                $(".psw").focus();
                $(".psw").select();
            } else {
                $scope.user.newPassword = hex_md5($scope.user.newPassword);
                AuthService.retrieve($scope.user).$promise.then(function (data) {
                    input_alert('密码重置成功', 1000);
                    setTimeout(function () {
                        $state.go("ucboot.login", {way: 0});
                    }, 1000);
                }, function (data) {
                    if (data.status == 405 || data.status == 404) {
                        input_alert("系统繁忙,请稍后再试", 1000);
                    } else {
                        input_alert(data.data.reason, 1000);
                    }
                })
            }
        }

    }])
    .controller('WxucController', ['$scope', '$state', 'AuthService', function ($scope, $state, AuthService) {
        UserChange(2);
        var userinfo = AuthService.getstrogecode();
        if (typeof (userinfo) == 'object' && userinfo.$promise) {
            userinfo.$promise.then(function (wxUserInfo) {
                $scope.wxUser = wxUserInfo;
            }, function (error) {
                $scope.error = JSON.stringify(error);
            });
        } else if (typeof (userinfo) == 'string') {
            if($storage.wxpay_openid){
                AuthService.getUserByName($storage.wxpay_openid).$promise.then(function(user){
                    $scope.wxUser = user;
                },function(error){
                    $scope.error = userinfo;
                })
            }else{
                $scope.error = userinfo;
            }
            //alert("userinfo is string");
        } else {
            //alert("userinfo is unknown");
            $scope.error = "未知错误";
            alert("未知错误");
        }
        //回退函数
        $scope.back = function () {
            if ($scope.wxUser.newuser) {
                window.history.go(-2);
            } else {
                window.history.back();
            }
        };
        $scope.wxLogin=function(){
            $storage.userId = $scope.wxUser.userid;
            $storage.name = $scope.wxUser.nickname;
            AuthService.shopCarMessage();
            $state.go('ucboot.myview');
        }
}])